<!--
 * @Date: 2022-03-02 17:53:09
 * @Author: 陶子
 * @LastEditTime: 2022-08-02 19:34:14
 * @FilePath: \jk_one-stop_pc\src\views\workManagement\productTask\BatchModal.vue
 * @pageName: 这是--(批量处理弹框)--页面
-->
<template>
  <div>
    <a-modal title="批量报工" :width="1200" :visible="showBatchModal" :maskClosable='false' :confirm-loading="modalLoading" @ok="submitProcess" @cancel="handleCancel">
      <a-table row-key="id" size="middle" :scroll="{ x: 1680, y: 300 }" :hideDefaultSelections="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle:' ',columnWidth:58, onChange: onSelectChange}" :columns="columns" :dataSource="tableData"
        :pagination="false" :loading="tableLoading" class="j-table-force-nowrap">
        <span slot="orderCode" slot-scope="text, record" class="btn-text" @click="orderDetail(record)">
          {{ record.orderCode }}
        </span>
        <span slot="operatorId" slot-scope="text, record, index">
          <a-select  @change="(u) => changeUser(u, index)" v-model="record.operatorId"  mode="multiple" allowClear style="width: 100%" placeholder="请选择">
            <a-select-option :value="item.value" v-for="(item,index) in record.operatorList" :key="index">
              {{item.text}}
            </a-select-option>
          </a-select>
        </span>
        <span slot="qualifiedNum" slot-scope="text, record, index">
          <a-input v-model="record.qualifiedNum" @blur='checkValue("qualifiedNum",index,record.qualifiedNum,record)'
            @input='formatInput("qualifiedNum",index,record.qualifiedNum)' style="width: 100%" placeholder="请输入" />
        </span>
        <span slot="notQualifiedNum" slot-scope="text, record, index">
          <a-input readOnly @click="showTable(index)" v-model="record.notQualifiedNum" style="width: 100%" placeholder="请输入" />
        </span>
        <span slot="notQualifiedReason" slot-scope="text, record">
          <!-- <a-select show-search v-model="record.notQualifiedReason" mode="multiple" style="width: 100%" placeholder="请选择" :filterOption="filterOption">
            <a-select-option v-for="(item,index) in dictOptions" :key="index" :value="item.value">
              {{ item.text || item.label }}
            </a-select-option>
          </a-select> -->
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{ record.notQualifiedReasonText || '请输入不合格数' }}</span>
            </template>
            <span><a-input v-model="record.notQualifiedReasonText" readonly placeholder="请输入" /></span>
          </a-tooltip>
        </span>
        <span slot="actions" slot-scope="text, record">
          <a @click="handleDelete(record)">删除</a>
        </span>
      </a-table>
      <!-- 全选/分页 -->
      <div style="padding-top:24px">
        <div style="display: inline-block">
          <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
          <span class='btn-text' style="margin:0 24px;cursor:pointer" @click="deleteAll">删除</span>
          <span style="margin-left: 8px">
            {{ `已选 ${selectedRowKeys.length}/${totalData.length} 项` }}
          </span>
        </div>
        <div style="display: inline-block; float: right">
          <a-pagination :total="totalData.length" v-model="current" :page-size-options="pageSizeOptions" :page-size="pageSize" @change="onChangePage"
            @showSizeChange="onShowSizeChange" show-quick-jumper show-size-changer />
        </div>
      </div>
      <div class="examBox">
        <Examine @submitProcess="submitProcess" type="0" id="MESS_TASK_REPORT_WORK_APPLY_FOR_PRODUCT" ref="examine" />
      </div>
    </a-modal>
    <a-modal
      title="不合格数输入"
      :visible="notQualifiedTable.visible"
      v-if="notQualifiedTable.visible"
      :confirm-loading="notQualifiedTable.confirmLoading"
      @ok="notQualifiedOk"
      @cancel="notQualifiedCancel"
    >
      <a-table :columns="notQualifiedTable.columns" :data-source="tableData[currentRowIndex].dataSource" :pagination="false">
        <span slot="notQualifiedNum" slot-scope="text, record, index">
          <a-input v-model="tableData[currentRowIndex].dataSource[index].notQualifiedNum" @input='(e) => inputNQNum(e, index)' placeholder="请输入" />
        </span>
      </a-table>
      <template slot="footer">
        <span style="float: left;line-height:33px">不合格原因：{{ tableData[currentRowIndex].reasonNum }} 不合格数：{{ tableData[currentRowIndex].num }}</span>
        <a-button key="back" @click="notQualifiedCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="notQualifiedOk">
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ajaxGetDictItems } from '@/api/api'
import { getReportTeamUserListByTaskId, reportBatchAdd } from '@/api/productOrder'
import { clearNoNum, accAdd, accSub } from '@/utils/util'
import Examine from '@/components/examine'
export default {
  components: { Examine },
  props: [],
  data() {
    return {
      currentLoginUser: {},
      dictOptions: [],
      showBatchModal: false,
      modalLoading: false,
      tableLoading: false,
      totalData: [], //所有的数据
      tableData: [], //表格展示数据
      selectedRowKeys: [],
      chooseArr: [],
      listIndeterminate: false,
      listCheckAll: false,
      current: 1,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30'],
      columns: [
        {
          title: '工单编号',
          align: 'left',
          dataIndex: 'orderCode',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'orderCode' },
        },
        {
          title: '工序名称',
          align: 'left',
          dataIndex: 'processName',
          ellipsis: true,
          width: 150,
        },
        {
          title: '报工单位',
          dataIndex: 'reportWorkUnitText',
          ellipsis: true,
          width: 90,
        },
        {
          title: '可报工数量',
          dataIndex: 'availableNumForReport',
          ellipsis: true,
          width: 120,
        },
        {
          title: '产品编号',
          align: 'left',
          dataIndex: 'goodsCode',
          ellipsis: true,
          width: 150,
        },
        {
          title: '产品名称',
          align: 'left',
          dataIndex: 'goodsName',
          ellipsis: true,
          width: 150,
        },

        {
          title: '规格',
          align: 'left',
          dataIndex: 'goodsSpec',
          ellipsis: true,
          width: 150,
        },
        {
          title: '基本单位',
          align: 'left',
          width: 120,
          dataIndex: 'goodsBasicUnitText',
          ellipsis: true,
        },

        {
          fixed: 'right',
          title: '操作人',
          align: 'left',
          dataIndex: 'operatorId',
          width: 150,
          ellipsis: true,
          scopedSlots: { customRender: 'operatorId' },
        },
        {
          fixed: 'right',
          title: '合格品数',
          dataIndex: 'qualifiedNum',
          ellipsis: true,
          width: 120,
          scopedSlots: { customRender: 'qualifiedNum' },
        },
        {
          fixed: 'right',
          title: '不合格品数',
          dataIndex: 'notQualifiedNum',
          ellipsis: true,
          width: 120,
          scopedSlots: { customRender: 'notQualifiedNum' },
        },
        {
          fixed: 'right',
          title: '不合格原因',
          dataIndex: 'notQualifiedReason',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'notQualifiedReason' },
        },
        {
          fixed: 'right',
          title: '操作',
          align: 'left',
          width: 60,
          dataIndex: 'actions',
          ellipsis: true,
          scopedSlots: { customRender: 'actions' },
        },
      ],
      notQualifiedTable: {
        visible: false,
        confirmLoading: false,
        reasonNum: 0,
        num: 0,
        dataSource: [],
        columns: [
          {
            title: '不合格原因',
            dataIndex: 'notQualifiedReasonText',
            ellipsis: true,
            width: '40%',
          },
          {
            title: '不合格数',
            dataIndex: 'notQualifiedNum',
            ellipsis: true,
            width: '50%',
            scopedSlots: { customRender: 'notQualifiedNum' },
          },
        ]
      },
      currentRowIndex: 0,
    }
  },
  watch: {
    totalData(newVal) {
      if (newVal.length > 10) {
        let arr = JSON.parse(JSON.stringify(newVal))
        this.tableData = arr.splice(0, 10)
      } else {
        this.tableData = newVal
      }
    },
  },
  created() {
    this.currentLoginUser = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
    ajaxGetDictItems('mess_not_qualified_reason', null).then((res) => {
      if (res.success) {
        this.dictOptions = res.result
      }
    })
  },
  methods: {
    changeUser(v, i) {
      this.tableData[i].operatorId = v
    },
    notQualifiedOk() {
      let reasons = []
      let reasonTexts = []
      let num = 0
      for (let i = 0; i < this.tableData[this.currentRowIndex].dataSource.length; i++) {
        const item = this.tableData[this.currentRowIndex].dataSource[i];
        if (item.notQualifiedNum) {
          num = parseInt(num * 10000)
          num += parseInt(Number(item.notQualifiedNum) * 10000)
          num = num / 10000
          if (Number(item.notQualifiedNum) > 0) {
            reasons.push(`${item.notQualifiedReason}:${item.notQualifiedNum} `)
            reasonTexts.push(`${item.notQualifiedReasonText}:${item.notQualifiedNum} `)
          }
        }
      }
      this.tableData[this.currentRowIndex].notQualifiedReason = reasons.join(',')
      this.tableData[this.currentRowIndex].notQualifiedReasonText = reasonTexts.join(',')
      this.tableData[this.currentRowIndex].notQualifiedNum = num
      this.tableData[this.currentRowIndex].currentData = JSON.parse(JSON.stringify(this.tableData[this.currentRowIndex].dataSource))
      // this.checkValue("notQualifiedNum",num)
      this.checkValue("notQualifiedNum",this.currentRowIndex,num,this.tableData[this.currentRowIndex])
      this.notQualifiedTable.visible = false
    },
    notQualifiedCancel() {
      this.notQualifiedTable.visible = false
    },
    showTable(i) {
      this.currentRowIndex = i
      this.tableData[this.currentRowIndex].dataSource = JSON.parse(JSON.stringify(this.tableData[this.currentRowIndex].currentData))
      let num = 0
      let reasonNum = 0
      for (let i = 0; i < this.tableData[this.currentRowIndex].dataSource.length; i++) {
        const item = this.tableData[this.currentRowIndex].dataSource[i];
        if (item.notQualifiedNum) {
          num = parseInt(num * 10000)
          num += parseInt(Number(item.notQualifiedNum) * 10000)
          num = num / 10000
          reasonNum += Number(item.notQualifiedNum) > 0 ? 1 : 0
        }
      }
      this.tableData[this.currentRowIndex].num = num
      this.tableData[this.currentRowIndex].reasonNum = reasonNum
      this.notQualifiedTable.visible = true
    },
    inputNQNum(e, index) {
      let num = 0
      let reasonNum = 0
      this.tableData[this.currentRowIndex].dataSource[index].notQualifiedNum = clearNoNum(e.target.value)
      for (let i = 0; i < this.tableData[this.currentRowIndex].dataSource.length; i++) {
        const item = this.tableData[this.currentRowIndex].dataSource[i];
        if (item.notQualifiedNum) {
          num = parseInt(num * 10000)
          num += parseInt(Number(item.notQualifiedNum) * 10000)
          num = num / 10000
          reasonNum += Number(item.notQualifiedNum) > 0 ? 1 : 0
        }
      }
      this.tableData[this.currentRowIndex].num = num
      this.tableData[this.currentRowIndex].reasonNum = reasonNum
    },
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    checkValue(type, index, value, row) {
      if (type == 'qualifiedNum') {
        let num = accSub(Number(row.excessCanReportNum), Number(row.notQualifiedNum ? row.notQualifiedNum : 0))
        if (Number(value) > Number(num)) {
          this.tableData[index][type] = ''
          row.reportWorkNum = row.notQualifiedNum
          this.$antdMessage.warning('报工总数不能大于最大应生产数！')
        } else {
          if (row.notQualifiedNum) {
            row.reportWorkNum = accAdd(Number(row.notQualifiedNum), Number(row.qualifiedNum))
          } else {
            row.reportWorkNum = row.qualifiedNum
          }
        }
      } else {
        // let num = accSub(
        //   Number(Number(row.reportWorkNum) ? Number(row.reportWorkNum) : row.excessCanReportNum),
        //   Number(value)
        // )
        // if (Number(num) > 0) {
        //   this.tableData[index].qualifiedNum = num
        // } else {
        //   this.tableData[index].qualifiedNum = 0
        // }
        // this.tableData[index].reportWorkNum = accAdd(
        //   Number(value),
        //   Number(this.tableData[index].qualifiedNum)
        // )
        let num = accSub(
          Number(this.tableData[index].excessCanReportNum),
          Number(this.tableData[index].qualifiedNum ? this.tableData[index].qualifiedNum : 0)
        );
        let qnum = accSub(
          Number(this.tableData[index].excessCanReportNum),
          Number(value)
        );
        if (Number(value) > Number(num)) {
          this.tableData[index].qualifiedNum = Number(qnum) > 0 ? qnum : 0
          this.tableData[index].reportWorkNum = accAdd(
            Number(value),
            Number(this.tableData[index].qualifiedNum)
          )
        } else {
          if (this.tableData[index].qualifiedNum) {
            this.tableData[index].reportWorkNum = accAdd(
              Number(this.tableData[index].notQualifiedNum),
              Number(this.tableData[index].qualifiedNum)
            );
          } else {
            this.tableData[index].reportWorkNum = this.tableData[index].notQualifiedNum;
          }
        }
        // let num = accSub(Number(row.excessCanReportNum), Number(row.qualifiedNum ? row.qualifiedNum : 0))
        // if (Number(value) > Number(num)) {
        //   this.tableData[index][type] = ''
        //   row.reportWorkNum = row.qualifiedNum
        //   this.$antdMessage.warning('报工总数不能大于最大应生产数！')
        // } else {
        //   if (row.qualifiedNum) {
        //     row.reportWorkNum = accAdd(Number(row.notQualifiedNum), Number(row.qualifiedNum))
        //   } else {
        //     row.reportWorkNum = row.notQualifiedNum
        //   }
        // }
      }
    },
    formatInput(type, index, value) {
      this.tableData[index][type] = clearNoNum(value)
    },

    showModal(selectArr) {
      let rejectArr = JSON.parse(JSON.stringify(selectArr))
      this.totalData = []
      for (let item of rejectArr) {
        item.qualifiedNum = item.availableNumForReport
        item.notQualifiedNum = ''
        item.notQualifiedReason = ''
        item.notQualifiedReasonText = ''
        item.reasonNum = 0
        item.num = 0
        let taskObj = {
          taskId: item.id,
        }
        getReportTeamUserListByTaskId(taskObj).then((res) => {
          if (res.success) {
            item.operatorList = res.result
            item.dataSource = this.dictOptions.map((dict) => {
              return {
                notQualifiedReasonText: dict.text,
                notQualifiedReason: dict.value,
                notQualifiedNum: ''
              }
            })
            item.currentData = JSON.parse(JSON.stringify(item.dataSource))
            for (let each of item.operatorList) {
              if (each.value == this.currentLoginUser.id) {
                item.operatorId = [each.value]
              }
            }
            this.totalData.push(item)
            this.showBatchModal = true
          } else {
            this.$antdMessage.warning(res.message)
          }
        })
      }
    },
    // 删除全部
    deleteAll() {
      if (this.selectedRowKeys.length > 0) {
        for (let item of this.selectedRowKeys) {
          this.totalData = this.totalData.filter((each) => {
            return each.id != item
          })
        }
        this.selectedRowKeys = []
        this.chooseArr = []
        this.checkBoxStatus()
      } else {
        this.$antdMessage.warning('请先选择数据')
      }
    },
    // 处理全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.chooseArr.push(item)
        }
      } else {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    // 删除处理列表
    handleDelete(row) {
      this.tableLoading = true
      setTimeout(() => {
        this.totalData = this.totalData.filter((each) => {
          return each.id != row.id
        })
        this.tableLoading = false
        this.current = 1
        this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
          return each != row.id
        })
        this.chooseArr = this.chooseArr.filter((item) => {
          return item.id != row.id
        })
      }, 300)
    },
    /* 工单详情 */
    orderDetail(v) {
      this.$router.push({
        path: '/workOrderDetail',
        query: {
          id: v.orderId,
        },
      })
    },
    inputNum(e, i) {},
    onSelectChange(selectedRowKeys, selectedRows) {
      this.chooseArr = this.chooseArr.concat(selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.checkBoxStatus()
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleOk(e)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    //点击确定按钮
    handleOk(e) {
      if (this.selectedRowKeys.length > 0) {
        this.chooseArr = this.chooseArr.filter((item, index) => {
          return this.chooseArr.findIndex((item1) => item1.id == item.id) == index
        })
        let selectArr = []
        for (let itemId of this.selectedRowKeys) {
          for (let itemData of this.chooseArr) {
            if (itemId == itemData.id) {
              selectArr.push(itemData)
            }
          }
        }
        console.log('看看去重的效果吧：', selectArr)
        this.submitForm(this.selectedRowKeys, selectArr, e)
      } else {
        this.$antdMessage.warning('请先选择数据')
      }
    },
    submitForm(idArr, dataArray, processDataVo) {
      for (let i = 0; i < dataArray.length; i++) {
        if (!dataArray[i].operatorId) {
          this.$antdMessage.warning(`所选数据第${i + 1}条，请选择操作人`)
          return
        }
        if (!dataArray[i].qualifiedNum && !dataArray[i].notQualifiedNum) {
          this.$antdMessage.warning(`所选数据第${i + 1}条，请输入合格品数或不合格品数`)
          return
        }
        if (dataArray[i].notQualifiedNum > 0 && dataArray[i].notQualifiedReason.length == 0) {
          this.$antdMessage.warning(`所选数据第${i + 1}条，不合格数大于0时，不合格原因必填`)
          return
        }
      }
      this.modalLoading = true
      let dtoList = []
      for (let item of dataArray) {
        let obj = {
          notQualifiedNum: item.notQualifiedNum ? item.notQualifiedNum : '',
          notQualifiedReason: item.notQualifiedReason,
          operatorId: item.operatorId instanceof Array ? item.operatorId.join(',') : item.operatorId,
          orderId: item.orderId,
          qualifiedNum: item.qualifiedNum ? item.qualifiedNum : '',
          reportWorkNum: item.reportWorkNum ? item.reportWorkNum : '',
          taskId: item.id,
          type: 'production',
        }
        dtoList.push(obj)
      }
      console.log('我要准备提交了啊：', dtoList)
      let parameter = {
        dtoList: dtoList,
        processDataVo: processDataVo,
      }
      reportBatchAdd(parameter).then((res) => {
        if (res.success) {
          this.$emit('reportBatchSuccess')
          this.handleCancel()
          this.$antdMessage.success('报工成功！')
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.modalLoading = false
      })
    },
    /* 取消处理 */
    handleCancel() {
      this.showBatchModal = false
      this.modalLoading = false
      this.tableLoading = false
      this.totalData = []
      this.tableData = []
      this.selectedRowKeys = []
      this.chooseArr = []
      this.listIndeterminate = false
      this.listCheckAll = false
      this.current = 1
      this.pageSize = 10
    },
    // 处理分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      let siz = pageSize * (current - 1)
      this.tableLoading = true
      setTimeout(() => {
        let arr = JSON.parse(JSON.stringify(this.totalData))
        this.tableData = arr.splice(siz, pageSize)
        this.tableLoading = false
        this.checkBoxStatus()
      }, 300)
    },
    onShowSizeChange(current, pageSize) {
      this.onChangePage(current, pageSize)
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.tableData) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log()
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
  },
}
</script> 

<style scoped lang='less'>
@import '~@/assets/less/public.less';
</style>